package utils

import (
	"fmt"
	"gitee.com/zjlsliupei/ghelp"
	"os"
	"os/exec"
	"path/filepath"
	"strings"
)

// CreateDir 创建目录，存在不处理
func CreateDir(dir string) error {
	if !ghelp.IsDir(dir) {
		return os.MkdirAll(dir, os.ModePerm)
	} else {
		return nil
	}
}

// ReplaceVar 替换模板变量
func ReplaceVar(str string, arg map[string]string) string {
	for k, v := range arg {
		str = strings.ReplaceAll(str, fmt.Sprintf("{{%s}}", k), v)
	}
	return str
}

// CreateFile 生成文件
func CreateFile(filePath string, content string, override bool) error {
	if ghelp.IsFile(filePath) && override == false {
		return nil
	}
	file, err := os.Create(filePath)
	if err != nil {
		return err
	}
	defer file.Close()
	_, err = file.WriteString(content)
	if err != nil {
		return err
	}
	return nil
}

// GetConfPathByDir 扫描目录，并返回指定后辍名的所有路径
func GetConfPathByDir(dir string, confExt string) ([]string, error) {
	var _dirs []string
	dirs, err := os.ReadDir(dir)
	if err != nil {
		return _dirs, err
	}
	for _, v := range dirs {
		f := filepath.Join(dir, v.Name())
		if filepath.Ext(f) == confExt && ghelp.IsFile(f) {
			_dirs = append(_dirs, f)
		}
	}
	return _dirs, nil
}

// StrFirstToUpper 首字母变成大写
func StrFirstToUpper(str string) string {
	if len(str) < 1 {
		return ""
	}
	strArry := []rune(str)
	if strArry[0] >= 97 && strArry[0] <= 122 {
		strArry[0] -= 32
	}
	return string(strArry)
}

// SnakeToCamelCase 蛇形变量转成大骆峰
func SnakeToCamelCase(snakeVar string) string {
	words := strings.Split(snakeVar, "_")
	var camel string
	for _, v := range words {
		camel += StrFirstToUpper(v)
	}
	return camel
}

// SnakeToCamelCaseForGorm 蛇形变量转成大骆峰只针对gorm， 处理特殊字段 id
func SnakeToCamelCaseForGorm(snakeVar string) string {
	words := strings.Split(snakeVar, "_")
	var camel string
	for _, v := range words {
		if v == "id" {
			camel += "ID"
		} else {
			camel += StrFirstToUpper(v)
		}
	}
	return camel
}

// ExecCommand 执行命令
func ExecCommand(args ...string) (string, error) {
	cmd := exec.Command(args[0], args[1:]...)
	output, err := cmd.CombinedOutput()
	// 脚本执行返回1 为报错
	return string(output), err
}
